<template>
  <div id="app">
    <el-container>
      <el-header>
        <div style="text-align: center">AGV呼叫系统</div>
        <div
          style="text-align: center; position: absolute; right: 100vm; top: 1%"
        >
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-s-tools"
            @click="dialogFormVisible = true"
            >设置</el-button
          >
        </div>
        <el-dialog
          title="设置"
          width="80%"
          :visible.sync="dialogFormVisible"
          @open="openSettingsDialog"
          @close="closeSettingsDialog"
        >
          <el-form :model="settings">
            <el-form-item label="选择线体" label-width="auto">
              <el-select
                v-model="settings.templateId"
                placeholder="请选择线体"
                :loading="tempLoadingFlag"
                loading-text="玩命加载中"
                @visible-change="templateSelecterDropDown"
              >
                <el-option
                  v-for="item in templates"
                  :key="item.id"
                  :label="item.template_name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="denfineSettings">确 定</el-button>
          </div>
        </el-dialog>
      </el-header>
      <el-main>
        <div class="main">
          <el-row type="flex" class="row1">
            <el-col :span="12" class="row1col1">
              <el-form label-width="80px">
                <el-form-item label="任务名称">
                  <el-tag :type="delicateTaks()" effect="dark" size="mini">{{
                    selectedTempName
                  }}</el-tag>
                </el-form-item>
                <el-form-item label="订单状态">
                  <el-tag
                    :type="currentOrderState.type"
                    effect="dark"
                    size="mini"
                    >{{ currentOrderState.msg }}</el-tag
                  >
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="12" class="row1col2">
              <el-progress
                type="circle"
                color="forestgreen"
                :stroke-width="10"
                :width="100"
                :percentage="percentage"
              ></el-progress>
            </el-col>
          </el-row>
          <el-row type="flex" class="row2">
            <el-col :span="24" class="row2col1">
              <el-button
                :type="btnCallAgvType()"
                round
                icon="el-icon-phone-outline"
                @click="callAgv"
                >呼叫AGV</el-button
              >
            </el-col>
          </el-row>
          <el-row type="flex" class="row3">
            <el-col :span="24" class="row3col1">
              <el-button
                round
                :type="btnHoldAndContinue().type"
                :icon="btnHoldAndContinue().icon"
                @click="holdAndContinueOrder"
                >{{ btnHoldAndContinue().msg }}</el-button
              >
              <el-button round icon="el-icon-delete" @click="cancelOrder"
                >取消任务</el-button
              >
            </el-col>
          </el-row>
        </div>
      </el-main>
      <el-footer
        >©2021 信息办OT科邹文轩. All rights reserved.
        <!-- <el-button @click="ceshi">测试</el-button> -->
      </el-footer>
    </el-container>
  </div>
</template>

<script>
export default {
  name: "app",
  components: {},
  data() {
    return {
      orderState: {
        unkown: { type: "info", msg: "未知" },
        waiting: { type: "warning", msg: "排队中" },
        cancel: { type: "danger", msg: "已取消" },
        execute: { type: "", msg: "执行中" },
        success: { type: "success", msg: "已完成" },
        hold: { type: "warning", msg: "暂停中" },
      },
      tempLoadingFlag: false,
      templates: [],
      dialogFormVisible: false,
      settings: {
        templateId: "",
      },
      orderId: null, //订单id
      callButtonState: false, //呼叫按钮按下标记
      token:
        "YWRtaW4sMTkzNTgyOTgyMDA5MixkYzJlZTJlZTMzNjVkZDFiMGJjZmY3N2Y0YzAwNzhhMg== ",
      currentOrderState: {},
      selectedTempName: "未选择",
      percentage: 0,
    };
  },
  // watch: {
  //   callButtonState: function (val) {
  //     if (val) {
  //       this.btnCallAgv.type = "success";
  //     } else {
  //       this.btnCallAgv.type = "primary";
  //     }
  //   },
  // },
  created() {
    this.currentOrderState = this.orderState.unkown;
  },
  mounted() {},
  destroyed() {
    window.clearInterval(this.$timer);
  },
  methods: {
    //定时查询订单信息
    cycleAskOrderInfo: function () {
      this.$timer = window.setInterval(() => {
        this.$http({
          method: "get",
          url: "/orders/" + this.orderId,
          params: {},
          headers: { token: this.token },
        })
          .then((res) => {
            // console.log(res.data);
            var state = res.data.order_state;
            if (
              state == "SUCCESS" ||
              state == "DELETED" ||
              state == "CANCELLED" ||
              state == "REJECTED"
            ) {
              //如果订单执行结束，则停止循环，按钮可按
              this.callButtonState = false;
              window.clearInterval(this.$timer);
              this.percentage = state == "SUCCESS" ? 100 : 0;
              if (state == "SUCCESS") {
                this.percentage = 100;
                this.currentOrderState = this.orderState.success;
              } else {
                this.percentage = 0;
                this.currentOrderState = this.orderState.cancel;
              }
            } else if (state == "EXECUTING") {
              var totalStepNum = res.data.mission.length;
              var currentStepNum = res.data.executing_index + 1;
              this.percentage =
                typeof totalStepNum != "undefined" && totalStepNum != 0
                  ? ((currentStepNum / totalStepNum) * 100).toFixed(1)
                  : 0;
              this.currentOrderState = this.orderState.execute;
            } else if (state == "QUEUEING") {
              this.currentOrderState = this.orderState.waiting;
            } else if (state == "HELD") {
              this.currentOrderState = this.orderState.hold;
            }
          })
          .catch((err) => {
            this.errProcess(err);
          });
      }, 1000);
    },

    //确定设置
    denfineSettings: function () {
      if (this.settings.templateId == "") {
        this.$message({
          showClose: true,
          message: "请先选择当前线体",
          type: "error",
        });
      } else {
        // console.log(this.settings.templateId);
        this.dialogFormVisible = false;
      }
    },

    //打开设置对话框
    openSettingsDialog: function () {
      window.clearInterval(this.$timer);
    },

    //选择器下拉事件，远程获取任务模板
    templateSelecterDropDown(flag) {
      if (flag) {
        this.tempLoadingFlag = true;
        this.$http({
          method: "get",
          url: "/templates/order",
          params: { page: "-1", filter_name: "" },
          headers: { token: this.token },
        })
          .then((res) => {
            this.tempLoadingFlag = false;
            var response = res.data;
            this.templates = response.templates.map((item) => {
              return {
                id: item.id,
                template_name: item.template_name,
              };
            });
            // console.log(this.templates);
          })
          .catch((err) => {
            this.tempLoadingFlag = false;
            this.errProcess(err);
          });
      }
    },

    //关闭设置对话框
    closeSettingsDialog() {
      this.callButtonState = false;
      if (this.settings.templateId) {
        this.selectedTempName = this.$linq
          .from(this.templates)
          .singleOrDefault(
            "x=>x.id==" + this.settings.templateId
          ).template_name;
        //查询当前执行的订单模板
        this.getExeOrderNum();
      }
    },

    //向指定订单发送命令
    sendOrderCmd: function (commandData, responseFunc, rejectFunc) {
      this.$http({
        method: "post",
        url: "/orders/" + this.orderId + "/command",
        params: {},
        data: commandData,
        headers: {
          token: this.token,
          "Content-Type": "application/json;charset=UTF-8",
        },
      })
        .then((res) => {
          responseFunc(res);
        })
        .catch((err) => {
          if (err) rejectFunc(err);
        });
    },

    //从订单模板创建订单
    createOrderFromTemplate: function (num) {
      this.$http({
        method: "post",
        url: "/orders/template/" + num,
        headers: {
          token: this.token,
          "Content-Type": "application/json;charset=UTF-8",
        },
        data: {},
      })
        .then((res) => {
          var response = res.data;
          // console.log(response);
          this.orderId = response.id; //获取分配的id并赋值
          this.$message({
            showClose: true,
            message: "订单下达成功",
            type: "success",
          });
          this.cycleAskOrderInfo(); //开始循环监听订单状态
        })
        .catch((err) => {
          this.errProcess(err);
          this.callButtonState = false;
        });
    },

    //获得当前模板在执行中的订单号
    getExeOrderNum() {
      this.$http({
        method: "get",
        url: "/orders/",
        params: { filter_by_state: 3, page: -1 },
        headers: { token: this.token },
      })
        .then((res) => {
          // console.log(res.data.orders);
          var orders = res.data.orders;
          var order = this.$linq
            .from(orders)
            .firstOrDefault("x=>x.template_id==" + this.settings.templateId);
          if (typeof order != "undefined") {
            this.orderId = order.id;
            this.callButtonState = true;
            this.cycleAskOrderInfo();
          } else {
            this.currentOrderState = this.orderState.unkown;
            this.percentage = 0;
            //查询当前队列的订单模板
            this.getQueueOrderNum();
          }
        })
        .catch((err) => {
          // console.log(err);
          this.errProcess(err);
        });
    },

    //获得当前模板在队列中的订单号
    getQueueOrderNum() {
      this.$http({
        method: "get",
        url: "/orders/",
        params: { filter_by_state: 1, page: -1 },
        headers: { token: this.token },
      })
        .then((res) => {
          // console.log(res.data.orders);
          var orders = res.data.orders;
          var order = this.$linq
            .from(orders)
            .firstOrDefault("x=>x.template_id==" + this.settings.templateId);
          // console.log(order);
          if (typeof order != "undefined") {
            this.orderId = order.id;
            // console.log(this.orderId);
            this.callButtonState = true;
            this.cycleAskOrderInfo();
          } else {
            this.currentOrderState = this.orderState.unkown;
            this.percentage = 0;
          }
        })
        .catch((err) => {
          // console.log(err);
          this.errProcess(err);
        });
    },

    //呼叫agv
    callAgv: function () {
      if (this.settings.templateId == "") {
        this.$message({
          showClose: true,
          message: "请先选择当前线体",
          type: "error",
        });
        return;
      } else if (this.callButtonState) {
        this.$message({
          showClose: true,
          message: "处理中，请耐心等待",
          type: "warning",
        });
        return;
      } else {
        this.callButtonState = true;
        this.percentage = 0;
        this.createOrderFromTemplate(this.settings.templateId);
      }
    },

    //取消呼叫
    cancelOrder: function () {
      if (!this.callButtonState) {
        this.$message({
          showClose: true,
          message: "非呼叫状态",
          type: "warning",
        });
      } else if (this.orderId == null) {
        this.$message({
          showClose: true,
          message: "无当前任务",
          type: "warning",
        });
      } else if (this.currentOrderState == this.orderState.waiting) {
        this.cancelOrderCMD();
      } else {
        this.$confirm("确定取消订单?", "提示", {
          customClass: "confirm_layout",
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            //按下确定
            this.cancelOrderCMD();
          })
          .catch(() => {});
      }
    },

    //取消订单命令
    cancelOrderCMD() {
      this.sendOrderCmd(
        { command_type: "CMD_ORDER_CANCEL" },
        (res) => {
          if (res) {
            this.$message({
              showClose: true,
              message: "订单取消成功",
              type: "success",
            });
            this.callButtonState = false;
          }
        },
        (err) => {
          this.errProcess(err);
        }
      );
    },

    //暂停订单
    holdAndContinueOrder: function () {
      if (this.orderId == null) {
        this.$message({
          showClose: true,
          message: "无当前任务",
          type: "warning",
        });
      } else if (this.currentOrderState == this.orderState.execute) {
        this.sendOrderCmd(
          { command_type: "CMD_ORDER_HELD" },
          (res) => {
            if (res) {
              this.$message({
                showClose: true,
                message: "订单暂停成功",
                type: "success",
              });
            }
          },
          (err) => {
            this.errProcess(err);
          }
        );
      } else if (this.currentOrderState == this.orderState.hold) {
        this.sendOrderCmd(
          {
            command_type: "CMD_ORDER_CONTINUE_FROM_HELD",
            disable_vehicle: false,
          },
          (res) => {
            if (res) {
              this.$message({
                showClose: true,
                message: "订单继续成功",
                type: "success",
              });
            }
          },
          (err) => {
            this.errProcess(err);
          }
        );
      } else {
        this.$message({
          showClose: true,
          message: "当前不可暂停",
          type: "warning",
        });
      }
    },

    //改变呼叫按钮外观
    btnCallAgvType() {
      if (this.callButtonState) {
        return "success";
      } else {
        return "";
      }
    },

    //改变任务指示状态
    delicateTaks() {
      if (this.selectedTempName == "未选择") {
        return "info";
      } else {
        return "success";
      }
    },

    btnHoldAndContinue() {
      if (this.currentOrderState == this.orderState.hold) {
        return { type: "warning", icon: "el-icon-video-play", msg: "继续任务" };
      } else {
        return { type: "", icon: "el-icon-video-pause", msg: "暂停任务" };
      }
    },

    //错误提示
    errProcess(err) {
      var msg = err.response.data.msg;
      if (typeof msg != "undefined" && msg != "") {
        this.$message({
          showClose: true,
          message: msg,
          type: "error",
        });
      } else {
        this.$message({
          showClose: true,
          message: "网络异常",
          type: "error",
        });
      }
    },

    // test(flag) {
    //   if (flag) console.log("haha");
    // },
    // ceshi() {
    //   this.sendOrderCmd(
    //     "CMD_ORDER_CANCEL",
    //     (res) => {
    //       console.log(res);
    //     },
    //     (err) => {
    //       console.log(err);
    //       this.$message({
    //         showClose: true,
    //         message: "测试",
    //         type: "error",
    //       });
    //     }
    //   );
    // },
  },
};
</script>

<style>
html,
body,
#app,
.el-container {
  padding: 0vw;
  margin: 0vw;
  height: 100vh;
}
.el-header,
.el-footer {
  background-color: #b3c0d1;
  color: #333;
  text-align: center;
  line-height: 60px;
}
.el-header {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  font-size: 20px;
}
.el-footer {
  font-size: 12px;
}
.el-main {
  background-color: lightblue;
  color: #333;
  height: 100%;
}
.main {
  display: flex;
  flex-direction: column;
  height: 100%;
  align-content: stretch;
  justify-content: space-between;
}
.row1 {
  flex-grow: 1;
  background-color: aliceblue;
}
.row2 {
  flex-grow: 1;
  background-color: darkgray;
}
.row3 {
  flex-grow: 1;
  background-color: darkgray;
}
.row1col1,
.row1col2,
.row2col1 {
  display: flex;
  justify-content: center;
  align-items: center;
}
.row3col1 {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.el-message-box.confirm_layout {
  width: 350px;
}
</style>

